package com.hunantv.mglive.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.hunantv.mglive.R;

/**
 * Created by 达 on 2015/12/4.
 */
public class GlideRoundTransform extends BitmapTransformation {

    private static int mViewWidth;

    public GlideRoundTransform(Context context) {
        this(context, 4);
    }

    public GlideRoundTransform(Context context, int dimenId) {
        super(context);
        try {
            mViewWidth = (int) context.getResources().getDimension(dimenId);
        } catch (Resources.NotFoundException e) {
            L.e(GlideRoundTransform.class.getSimpleName(), e);
            mViewWidth = dimenId;
        }
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return roundCrop(pool, toTransform);
    }

    private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;
        int width = source.getWidth();
        int height = source.getHeight();
        if (width > height) {
            width = height;
        } else {
            height = width;
        }

        Bitmap result = pool.get(width, height, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        RectF rectF = new RectF(1f, 1f, width - 2, height - 2);
        canvas.drawRoundRect(rectF, width, width, paint);
        return result;
    }

    @Override
    public String getId() {
        return getClass().getName() + Math.round(mViewWidth);
    }
}

